package bma.common.netty.framereader;

import org.jboss.netty.buffer.ChannelBuffer;

import bma.common.netty.framereader.FrameReader.RESULT;

/**
 * 帧读取的根对象
 * 
 * @author guanzhong
 * 
 * @param <CTX_TYPE>
 */
public abstract class FrameReaderRoot<CTX_TYPE> {

	private FrameReader<CTX_TYPE> reader;
	private transient CTX_TYPE context;

	public FrameReaderRoot() {
		super();
	}

	public FrameReaderRoot(FrameReader<CTX_TYPE> reader) {
		super();
		this.reader = reader;
	}

	public FrameReader<CTX_TYPE> getReader() {
		return reader;
	}

	public void setReader(FrameReader<CTX_TYPE> reader) {
		this.reader = reader;
	}

	public abstract CTX_TYPE createContext();

	public abstract Object getModelFromContext(CTX_TYPE ctx);

	/**
	 * 处理输入的数据
	 * 
	 * @param buffer
	 * @return
	 */
	public Object process(ChannelBuffer buffer) throws Exception {
		if (reader == null) {
			throw new NullPointerException("frameReader");
		}
		if (context == null) {
			// 新请求
			context = createContext();
		}

		while (true) {
			RESULT r = reader.process(buffer, context);
			switch (r) {
			case AGAIN:
			case DONE:
				continue;
			case NOT_DONE:
				return null;
			case END:
				break;
			}

			Object o = getModelFromContext(context);
			context = null;
			return o;
		}
	}
}
